package ebcs.scan.service.sys.fileStorage.impl;

 import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ebcs.database.bean.sys.FileStorage;
import ebcs.database.service.sys.IFileStorageDBService;
import ebcs.scan.bean.sys.FileStorageBean;
import ebcs.scan.common.consts.KPlatSysConsts;
import jplat.error.exception.JTransException;
import jplat.tools.config.JBusConfig;
import jplat.tools.file.XFileTools;
import jplat.tools.string.DateUtil;
import jplat.tools.string.JRandomUtil;
import jplat.tools.string.StringUtil;

@Service
public class FileStorageServiceImpl implements ebcs.scan.service.sys.fileStorage.FileStorageService {

	
	private Logger logger = Logger.getLogger(FileStorageServiceImpl.class);
	@Autowired
	IFileStorageDBService fileStorageService;
	
	@Override
	public String writeToFileStorage(FileStorageBean fileStorage) throws JTransException{
		
		FileStorage fileSt = new FileStorage();
		fileSt.setStorageName(fileStorage.getStorageName());
		fileSt.setEntityName(fileStorage.getEntityName());
		fileSt.setEntityNo(fileStorage.getEntityNo());
		fileSt.setEntityType(fileStorage.getEntityType());
		if(StringUtil.isEmpty(fileStorage.getUserNo())){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"上传文件时，[userNo] 不能为空！");
		}
		if(fileStorage.getFileData()==null){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"上传文件时，[fileData] 不能为空！");
		}
		fileSt.setStoragePath(fileStorage.getUserNo()+"/"+DateUtil.getSystemTimeBySomeFormat("yyyyMMdd"));
		String storageId =JRandomUtil.getUUID();
		fileSt.setStorageId(storageId);
		fileSt.setCreateDate(DateUtil.today());
		fileSt.setUpdateDate(DateUtil.today());
 		int i = fileStorageService.insert(fileSt);
 		if(i>0){
 			XFileTools.writeFile(JBusConfig.FILE_SERVICE_PATH+fileSt.getStoragePath()+"/"+fileSt.getStorageId(), fileStorage.getFileData());
 		}else{
 			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"文件存储失败！");
 		}
		 
		return storageId;
	}

	
	@Override
	public FileStorage writeToFileStorageReturnObject(FileStorageBean fileStorage) throws JTransException{
		
		FileStorage fileSt = new FileStorage();
		fileSt.setStorageName(fileStorage.getStorageName());
		fileSt.setEntityName(fileStorage.getEntityName());
		fileSt.setEntityNo(fileStorage.getEntityNo());
		fileSt.setEntityType(fileStorage.getEntityType());
		if(StringUtil.isEmpty(fileStorage.getUserNo())){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"上传文件时，[userNo] 不能为空！");
		}
		if(fileStorage.getFileData()==null){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"上传文件时，[fileData] 不能为空！");
		}
		fileSt.setStoragePath(fileStorage.getUserNo()+"/"+DateUtil.getSystemTimeBySomeFormat("yyyyMMdd"));
		String storageId =JRandomUtil.getUUID();
		fileSt.setStorageId(storageId);
		fileSt.setCreateDate(DateUtil.today());
		fileSt.setUpdateDate(DateUtil.today());
 		int i = fileStorageService.insert(fileSt);
 		if(i>0){
 			XFileTools.writeFile(JBusConfig.FILE_SERVICE_PATH+fileSt.getStoragePath()+"/"+fileSt.getStorageId(), fileStorage.getFileData());
 		}else{
 			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"文件存储失败！");
 		}
		 
		return fileSt;
	}
	@Override
	public byte[] loadFileInStorage(String storageId) throws JTransException {
		
		if(StringUtils.isEmpty(storageId)){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"下传文件时，[storageId] 不能为空！");
		}
		FileStorage fileSt = new FileStorage();
		fileSt.setStorageId(storageId);
		FileStorage filestorage = this.fileStorageService.seachFileStorgeById(fileSt);
		byte[]  fileByte = null;
		try {
			fileByte = XFileTools.loadFile(JBusConfig.FILE_SERVICE_PATH+filestorage.getStoragePath()+"/"+filestorage.getStorageId());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("文件查询失败:"+e.getMessage());
			throw  new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"文件查询失败！");
		}
		return fileByte;
	}
	
	
	@Override
	public FileStorageBean loadFileStoragEntity(String storageId) throws JTransException {
		
		if(StringUtils.isEmpty(storageId)){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"下传文件时，[storageId] 不能为空！");
		}
		FileStorage fileSt = new FileStorage();
		fileSt.setStorageId(storageId);
		FileStorage filestorage = this.fileStorageService.seachFileStorgeById(fileSt);
		byte[]  fileByte = null;
		try {
			fileByte = XFileTools.loadFile(JBusConfig.FILE_SERVICE_PATH+filestorage.getStoragePath()+"/"+filestorage.getStorageId());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("文件查询失败:"+e.getMessage());
			throw  new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"文件查询失败！");
		}
		FileStorageBean fileBean = new FileStorageBean();
		fileBean.setFileData(fileByte);
		fileBean.setStorageName(filestorage.getStorageName());
		return fileBean;
	}

	@Override
	public String loadFileInStorage(String storageId, String charset) throws JTransException {
		if(StringUtils.isEmpty(storageId)){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"下传文件时，[storageId] 不能为空！");
		}
		FileStorage fileSt = new FileStorage();
		fileSt.setStorageId(storageId);
		FileStorage filestorage = this.fileStorageService.seachFileStorgeById(fileSt);
		String fileStr = null;
		fileStr = XFileTools.loadFile(filestorage.getStoragePath(), charset);
		return fileStr;
	}


	@Override
	public int updateFileStorage(String storageId, String entityNo, String entityName,String entityType) {
		FileStorage fileStDb = new FileStorage();
		fileStDb.setStorageId(storageId);
		fileStDb.setEntityName(entityName);
		fileStDb.setEntityNo(entityNo);
		fileStDb.setEntityType(entityType);
		return this.fileStorageService.updateFileStorge(fileStDb);
	}


	@Override
	public FileStorageBean searchLatelyFileStorageList(String entityNo,String entityName,String entityType) {
		FileStorage fileStDb = new FileStorage();
		fileStDb.setEntityName(entityName);
		fileStDb.setEntityNo(entityNo);
		fileStDb.setEntityType(entityType);
		List<FileStorage> fileStList = this.fileStorageService.searchFileStorageByEntityInfor(fileStDb);
		FileStorageBean rsFileSt = null;
		if(fileStList.size()>0) {
			 FileStorage fileSt = fileStList.get(0);
			 rsFileSt = getFileImageUrlList(fileSt);
		}
		return rsFileSt;
	}


	private FileStorageBean getFileImageUrlList(FileStorage fileSt) {
		FileStorageBean rsFileSt = new FileStorageBean();
			rsFileSt.setEntityName(fileSt.getEntityName());
			rsFileSt.setEntityNo(fileSt.getEntityNo());
			rsFileSt.setEntityType(fileSt.getEntityType());
			rsFileSt.setFileExtension(fileSt.getFileExtension());
			rsFileSt.setStorageName(fileSt.getStorageName());
			rsFileSt.setDownloadUrl(String.format(JBusConfig.APP_URL+"/ns0/sys/file/%s/fileDownload.do", new Object[] {fileSt.getStorageId()}));
			List imagUrlList = new ArrayList();
			if(fileSt.getPdfLength() != null) {
				for(int i=1 ;i<= fileSt.getPdfLength().intValue();i++) {
					imagUrlList.add(JBusConfig.STATIC_SERVICE_URL + String.format(fileSt.getStoragePath()+"/%s", new Object[] { fileSt.getStorageId() +"-"+i+".png"}));
				}
			}else {
				imagUrlList.add(JBusConfig.STATIC_SERVICE_URL + String.format(fileSt.getStoragePath()+"/%s", new Object[] { fileSt.getStorageId() }));
			}
			rsFileSt.setImagUrlList(imagUrlList);
			rsFileSt.setStorageId(fileSt.getStorageId());
 		return rsFileSt;
	}
	
	public int updatePdfLength(String storageId,int pdfLength) {
		FileStorage fileStDb = new FileStorage();
		fileStDb.setStorageId(storageId);
		fileStDb.setPdfLength(pdfLength);
		return fileStorageService.updateFileStorge(fileStDb);
	}


	@Override
	public FileStorageBean searchFileStorageByStorageId(String storageId) {
		// TODO Auto-generated method stub
		FileStorage fileStDb = new FileStorage();
		fileStDb.setStorageId(storageId);
		FileStorage searchFileStorage = this.fileStorageService.seachFileStorgeById(fileStDb);
		FileStorageBean rsFileSt = new FileStorageBean();
		if(searchFileStorage!=null) {
			rsFileSt = getFileImageUrlList(searchFileStorage);
		}
		return rsFileSt;
	}
	
}
